package mavenWebProject;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * Servlet implementation class PurchaseServlet
 */
@WebServlet("/PurchaseServlet")
public class PurchaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PurchaseServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		Date date=new Date();
		String opentime=(1900+date.getYear())+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日";
		HttpSession session=request.getSession();
		String username=(String) session.getAttribute("username");
		//1.加载mybatis的核心配置文件，获取sqlsessionfactory
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		
		//2.获取sqlsession对象，用它来执行sql
		SqlSession sqlsession=sqlSessionFactory.openSession();
		
		//3.获取mapper接口的代理对象
		productsMapper mapper=sqlsession.getMapper(productsMapper.class);
		String name="";String img="";String size="";String price="";String amount="";String stage="待发货";int id=-1;
		try {id=Integer.valueOf(request.getParameter("orderId"));}catch(Exception e) {}
		if(id==-1) {
			name=request.getParameter("name");
			img=request.getParameter("img");
			size=request.getParameter("size");
			price=request.getParameter("price");
			amount=request.getParameter("num");
		}else {
			List<car> car=mapper.selectCarById(id);
			for(car s:car) {
				img=s.getImg();name=s.getName();size=s.getSize();amount=String.valueOf(s.getAmount());price=String.valueOf(s.getPrice());
				mapper.deleteFromCar(username, id);
			}
		}
		
		List<order> order=mapper.selectOrderSame(username, name, size, opentime, stage);
		List<products> products=mapper.selectByName(name);int status=-1;
		for(products s:products) {status=s.getStatus();}
		if(status==1) {
		if(order.isEmpty()) {
			String closetime="-1";
			mapper.insertIntoOrder(username, img, name,Integer.valueOf(price), Integer.valueOf(amount), size, stage, opentime,closetime);
			int money=Integer.valueOf(price)*Integer.valueOf(amount);
			userMapper usermapper=sqlsession.getMapper(userMapper.class);
			List<user> user=usermapper.selectByUsername(username);
			int usermoney=0;
			for(user s:user) {
				usermoney=s.getMoney();
			}
			mapper.updateChangeStorage(Integer.valueOf(amount), name);
			if(usermoney>=money) {
				mapper.updateChangeMoney(money, username);
				mapper.updateChangeMoney(-(money), "系统账户");
				sqlsession.commit();
				request.getRequestDispatcher("messagePage.jsp?message=创建订单成功").forward(request, response);
			}else {
				request.getRequestDispatcher("messagePage.jsp?message=资金不足，请充值").forward(request, response);
			}
		}else {
			mapper.updateOrderAmount(Integer.valueOf(amount),username,name,size,opentime,stage);
			int money=Integer.valueOf(price)*Integer.valueOf(amount);
			userMapper usermapper=sqlsession.getMapper(userMapper.class);
			List<user> user=usermapper.selectByUsername(username);
			int usermoney=0;
			for(user s:user) {
				usermoney=s.getMoney();
			}
			mapper.updateChangeStorage(Integer.valueOf(amount), name);
			if(usermoney>=money) {
				mapper.updateChangeMoney(money, username);
				mapper.updateChangeMoney(-(money), "系统账户");
				sqlsession.commit();
				sqlsession.commit();
				request.getRequestDispatcher("messagePage.jsp?message=增加该订单").forward(request, response);
			}else {
				request.getRequestDispatcher("messagePage.jsp?message=资金不足，请充值").forward(request, response);
			}
		}
		}else {
			request.getRequestDispatcher("messagePage.jsp?message=该商品已下架").forward(request, response);
		}
		sqlsession.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
